import { _decorator, Component, Node } from 'cc';
import { UIRoot } from '../../script/common/ui/UIRoot';
import { EditBox } from 'cc';
import WebSock from '../../sgame/Socket/WebSock';
import { instantiate } from 'cc';
import { jsonProtoCoder } from '../../script/common/socket/JsonProtoCoder';
import { SOCKET_CLOSE_CODE } from '../../sgame/Socket/ISocket';
const { ccclass, property } = _decorator;

/**
 * 服务器测试代码在 test/socket/jsonserver.js
 */
@ccclass('JsonSocketTest')
export class JsonSocketTest extends UIRoot {
    private _sock: WebSock = null;
    private connectNode: Node;
    private urlEb: EditBox;

    private closeNode: Node;

    private sendNode: Node;
    private sendEb: EditBox;

    private receiveNode: Node;
    private receiveContentNode: Node;
    private receiveItem: Node;

    run(): void {
        // 连接
        this.connectNode = this.guiRoot.Child('connect');
        this.urlEb = this.connectNode.Component('url', EditBox);

        // 关闭连接
        this.closeNode = this.guiRoot.Child('close');

        // 发送
        this.sendNode = this.guiRoot.Child('send');
        this.sendEb = this.sendNode.Component('content', EditBox);

        // 接收
        this.receiveNode = this.guiRoot.Child('receive');
        this.receiveContentNode = this.receiveNode.Child('content/view/content');
        this.receiveItem = this.receiveContentNode.Child('item');

        this.closeNode.OnClickChild('close', () => {
            this._sock.close(SOCKET_CLOSE_CODE.NORMAL);
        });

        this.connectNode.OnClickChild('connect', () => {
            this._sock = new WebSock(this.urlEb.string, jsonProtoCoder);

            let callback = () => {
                this.changeStatus(false);
            };

            this._sock.closeCallback(callback);
            this._sock.connect(() => {
                this.changeStatus(true);
            }, callback);

            let receiveCallback = (data: string) => {
                let node = instantiate(this.receiveItem);
                node.setParent(this.receiveContentNode);
                node.active = true;
                node.Label(data);
            };

            this._sock.on(1, receiveCallback);
            this._sock.on(2, receiveCallback);
        });

        this.sendNode.OnClickChild("send", () => {
            this._sock.send(1, this.sendEb.string);
            this.sendEb.string = "";
        });

        this.sendNode.OnClickChild("sendHalt", () => {
            this._sock.sendHalt(2, this.sendEb.string);
            this.sendEb.string = "";
        });
    }

    changeStatus(isConnect: boolean) {
        this.connectNode.active = !isConnect;
        this.receiveNode.active = isConnect;
        this.closeNode.active = isConnect;
        this.sendNode.active = isConnect;
        if (!isConnect) {
            this._sock.off(1);
        }
    }
}